package com.yanggu.payment.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeCloseModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yanggu.payment.entity.OrderInfo;
import com.yanggu.payment.enums.OrderStatus;
import com.yanggu.payment.enums.PayType;
import com.yanggu.payment.service.AliPayService;
import com.yanggu.payment.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @version V1.0
 * @author: YangGu
 * @date: 2022/5/15 11:49
 * @description:
 */
@Component
@Slf4j
public class AliPayTask {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private AlipayClient alipayClient;

    /**
     * 每隔30秒查询5分钟内未使用支付宝支付的订单
     * 手动调用支付宝查询订单API, 查询订单是否支付, 如果订单已经支付, 修改商户订单状态为支付成功
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void confirmOrderPayOrNot() throws AlipayApiException {
        //查询所有5分钟内未支付的订单
        LambdaQueryWrapper<OrderInfo> wrapper = Wrappers.<OrderInfo>lambdaQuery()
                .eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType())
                .eq(OrderInfo::getPaymentType, PayType.ALIPAY.getType())
                .gt(OrderInfo::getCreateTime, DateUtil.offsetMinute(new Date(), -5));
        List<OrderInfo> list = orderInfoService.list(wrapper);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        for (OrderInfo orderInfo : list) {
            //调用支付宝查单API(根据订单号和商户号)
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            String orderNo = orderInfo.getOrderNo();
            model.setOutTradeNo(orderNo);
            request.setBizModel(model);
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                log.warn("支付宝查单接口调用失败, 返回数据: {}", JSON.toJSONString(response));
                continue;
            }

            String tradeStatus = response.getTradeStatus();
            //如果订单的状态不是TRADE_SUCCESS和TRADE_FINISHED退出
            if (!StrUtil.equals("TRADE_SUCCESS", tradeStatus) && !StrUtil.equals("TRADE_FINISHED", tradeStatus)) {
                continue;
            }

            aliPayService.handlerPaySuccess(orderInfo, response.getTradeNo(), tradeStatus);
        }
    }

    /**
     * 每隔30s执行关闭超时且未支付的订单
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void closeTimeOutOrder() throws AlipayApiException {
        //查询所有未支付的订单
        LambdaQueryWrapper<OrderInfo> wrapper = Wrappers.<OrderInfo>lambdaQuery()
                .eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType())
                .eq(OrderInfo::getPaymentType, PayType.ALIPAY.getType())
                .le(OrderInfo::getCreateTime, DateUtil.offsetMinute(new Date(), -5))
                ;
        List<OrderInfo> list = orderInfoService.list(wrapper);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        for (OrderInfo tempOrder : list) {
            //修改订单状态为关闭
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setId(tempOrder.getId());
            orderInfo.setOrderStatus(OrderStatus.CLOSED.getType());
            orderInfoService.updateById(orderInfo);

            //调用支付宝取消订单API
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            AlipayTradeCloseModel model = new AlipayTradeCloseModel();
            model.setOutTradeNo(tempOrder.getOrderNo());
            request.setBizModel(model);
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        }
    }

}
